import { useState, useMemo } from 'react'
import {
  Calendar,
  Badge,
  Modal,
  List,
  Typography,
  Tag,
  Space,
  Tooltip,
  Form,
  Input,
  DatePicker,
  InputNumber,
  message,
  Select,
  Button,
  Card,
} from 'antd'
import {
  ClockCircleOutlined,
  CalendarOutlined,
  EditOutlined,
  SearchOutlined,
  ReloadOutlined,
  ExclamationCircleOutlined,
  CheckCircleOutlined,
  WarningOutlined,
} from '@ant-design/icons'
import dayjs from 'dayjs'
import { validateWorkTimeData } from '../utils/dataParser'
import {
  isWorkday as isWorkdayUtil,
  getRequiredHours,
  getDayTypeDescription,
  getHolidayInfo,
} from '../utils/holidayUtils'

const { Text } = Typography

const { TextArea } = Input

const WorkTimeCalendar = ({
  data = [],
  originalData = [],
  onEditRecord,
  onDeleteRecord,
  onFilterData,
}) => {
  const [selectedDate, setSelectedDate] = useState(null)
  const [modalVisible, setModalVisible] = useState(false)
  const [selectedDateData, setSelectedDateData] = useState([])
  const [editModalVisible, setEditModalVisible] = useState(false)
  const [editingRecord, setEditingRecord] = useState(null)
  const [editForm] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const [filters, setFilters] = useState({
    keyword: '',
    project: 'all',
    product: 'all',
  })

  // 获取筛选选项
  const filterOptions = useMemo(() => {
    const projects = new Set()
    const products = new Set()

    originalData.forEach((item) => {
      if (item.project) projects.add(item.project)
      if (item.product) products.add(item.product)
    })

    return {
      projects: Array.from(projects).sort(),
      products: Array.from(products).sort(),
    }
  }, [originalData])

  // 按日期分组工时数据
  const dataByDate = useMemo(() => {
    const grouped = new Map()
    data.forEach((item) => {
      if (!item.date) return
      const dateKey = item.date
      if (!grouped.has(dateKey)) {
        grouped.set(dateKey, [])
      }
      grouped.get(dateKey).push(item)
    })
    return grouped
  }, [data])

  // 获取日期的工时数据
  const getDateData = (date) => {
    const dateString = date.format('YYYY-MM-DD')
    return dataByDate.get(dateString) || []
  }

  // 检查是否是工作日（包含节假日和调休逻辑）
  const isWorkday = (date) => {
    return isWorkdayUtil(date)
  }

  // 检查工时是否完成（工作日需要标准工时）
  const checkHoursCompletion = (date, totalHours) => {
    const requiredHours = getRequiredHours(date)
    const isWorkdayToday = isWorkday(date)

    if (!isWorkdayToday) {
      return {
        isComplete: true,
        required: 0,
        actual: totalHours,
        isWorkday: false,
        dayTypeDescription: getDayTypeDescription(date),
      }
    }

    const isComplete = totalHours >= requiredHours
    const today = dayjs()
    const isToday = date.isSame(today, 'day')
    const isPastDate = date.isBefore(today, 'day')

    return {
      isComplete,
      required: requiredHours,
      actual: totalHours,
      shortage: isComplete ? 0 : requiredHours - totalHours,
      isToday,
      isPastDate,
      isWorkday: true,
      dayTypeDescription: getDayTypeDescription(date),
    }
  }

  // 日历单元格渲染 - 日期视图
  const renderDateCell = (date) => {
    const dateData = getDateData(date)
    const totalHours = dateData.reduce(
      (sum, item) => sum + (item.hours || 0),
      0
    )
    const projects = [
      ...new Set(dateData.map((item) => item.project).filter(Boolean)),
    ]

    // 检查工时完成情况
    const hoursCheck = checkHoursCompletion(date, totalHours)
    const isWorkdayToday = isWorkday(date)

    // 如果是工作日但没有任何工时记录，显示提示
    if (isWorkdayToday && dateData.length === 0) {
      const emptyWorkdayCheck = checkHoursCompletion(date, 0)
      const warningText = emptyWorkdayCheck.isPastDate ? '已逾期' : '待录入'
      const warningColor = emptyWorkdayCheck.isPastDate ? '#ff4d4f' : '#fa8c16'

      return (
        <div style={{ fontSize: '12px' }}>
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              color: warningColor,
              fontWeight: 'bold',
            }}
          >
            <ExclamationCircleOutlined
              style={{
                marginRight: '4px',
                fontSize: '14px',
              }}
            />
            <span>{warningText}</span>
          </div>
          <div
            style={{
              textAlign: 'center',
              fontSize: '10px',
              color: '#999',
              marginTop: '2px',
            }}
          >
            需要{emptyWorkdayCheck.required}小时
          </div>
          <div
            style={{
              textAlign: 'center',
              fontSize: '10px',
              color: '#999',
              marginTop: '1px',
            }}
          >
            {emptyWorkdayCheck.dayTypeDescription}
          </div>
        </div>
      )
    }

    // 如果没有数据且不是工作日，显示节假日信息
    if (dateData.length === 0) {
      const holidayInfo = getHolidayInfo(date)

      if (holidayInfo) {
        return (
          <div style={{ fontSize: '12px', textAlign: 'center' }}>
            <div
              style={{
                color: holidayInfo.isOffDay ? '#52c41a' : '#fa8c16',
                fontWeight: 'bold',
                fontSize: '11px',
              }}
            >
              {holidayInfo.name}
            </div>
            <div
              style={{
                fontSize: '10px',
                color: '#999',
                marginTop: '1px',
              }}
            >
              {holidayInfo.isOffDay ? '放假' : '调休上班'}
            </div>
          </div>
        )
      }

      return null
    }

    // 根据工时完成情况确定显示颜色和图标
    let hoursColor, hoursIcon
    if (isWorkdayToday) {
      if (hoursCheck.isComplete) {
        hoursColor = '#52c41a' // 绿色 - 完成
        hoursIcon = <CheckCircleOutlined style={{ marginRight: '4px' }} />
      } else {
        // 根据是否过期设置不同的颜色
        hoursColor = hoursCheck.isPastDate ? '#ff4d4f' : '#fa8c16' // 红色 - 逾期，橙色 - 当日不足
        hoursIcon = hoursCheck.isPastDate ? (
          <WarningOutlined style={{ marginRight: '4px' }} />
        ) : (
          <ExclamationCircleOutlined style={{ marginRight: '4px' }} />
        )
      }
    } else {
      hoursColor = '#1890ff' // 蓝色 - 非工作日
      hoursIcon = <ClockCircleOutlined style={{ marginRight: '4px' }} />
    }

    return (
      <div style={{ fontSize: '12px' }}>
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            marginBottom: '2px',
            color: hoursColor,
            fontWeight: 'bold',
          }}
        >
          {hoursIcon}
          <span>{totalHours}h</span>
          {isWorkdayToday && !hoursCheck.isComplete && (
            <span
              style={{
                fontSize: '10px',
                color: '#ff4d4f',
                marginLeft: '4px',
              }}
            >
              (-{hoursCheck.shortage}h)
            </span>
          )}
        </div>

        {/* 日期类型描述 */}
        <div
          style={{
            fontSize: '10px',
            color: '#999',
            marginBottom: '2px',
          }}
        >
          {hoursCheck.dayTypeDescription}
        </div>

        {/* 工时完成提示 */}
        {isWorkdayToday && hoursCheck.shortage > 0 && (
          <div
            style={{
              fontSize: '10px',
              color: hoursCheck.isComplete ? '#52c41a' : '#ff4d4f',
              marginBottom: '2px',
            }}
          >
            {`还需${hoursCheck.shortage}h`}
          </div>
        )}

        <div style={{ maxHeight: '60px', overflowY: 'auto' }}>
          {dateData.slice(0, 2).map((item, index) => (
            <div
              key={index}
              style={{
                fontSize: '11px',
                color: '#666',
                marginBottom: '1px',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
              }}
            >
              {item.content.length > 15
                ? `${item.content.substring(0, 15)}...`
                : item.content}
            </div>
          ))}
          {dateData.length > 2 && (
            <div style={{ fontSize: '11px', color: '#999' }}>
              还有 {dateData.length - 2} 项...
            </div>
          )}
        </div>

        {projects.length > 0 && (
          <div style={{ marginTop: '2px' }}>
            {projects.slice(0, 2).map((project, index) => (
              <Tag
                key={index}
                size='small'
                style={{ fontSize: '10px', marginRight: '2px' }}
              >
                {project.length > 8 ? `${project.substring(0, 8)}...` : project}
              </Tag>
            ))}
          </div>
        )}
      </div>
    )
  }

  // 日历单元格渲染 - 月份视图
  const renderMonthCell = (date) => {
    const monthData = data.filter((item) => {
      if (!item.date) return false
      const itemDate = dayjs(item.date)
      return itemDate.format('YYYY-MM') === date.format('YYYY-MM')
    })

    if (monthData.length === 0) return null

    const totalHours = monthData.reduce(
      (sum, item) => sum + (item.hours || 0),
      0
    )
    const totalDays = new Set(monthData.map((item) => item.date)).size

    return (
      <div style={{ fontSize: '12px', textAlign: 'center' }}>
        <div style={{ color: '#1890ff', fontWeight: 'bold' }}>
          {totalHours}h
        </div>
        <div style={{ color: '#666' }}>{totalDays}天</div>
      </div>
    )
  }

  // 统一的单元格渲染函数
  const cellRender = (current, info) => {
    const { type } = info

    if (type === 'date') {
      return renderDateCell(current)
    } else if (type === 'month') {
      return renderMonthCell(current)
    }

    return null
  }

  // 处理日期选择
  const handleDateSelect = (date) => {
    const dateData = getDateData(date)
    if (dateData.length > 0) {
      setSelectedDate(date)
      setSelectedDateData(dateData)
      setModalVisible(true)
    }
  }

  // 处理日期点击
  const handleDateClick = (date) => {
    handleDateSelect(date)
  }

  // 日历面板改变时的处理
  const handlePanelChange = (date, mode) => {
    console.log('Panel changed:', date.format('YYYY-MM-DD'), mode)
  }

  // 处理筛选
  const handleFilter = () => {
    onFilterData && onFilterData(filters)
  }

  // 重置筛选
  const handleResetFilter = () => {
    const resetFilters = {
      keyword: '',
      project: 'all',
      product: 'all',
    }
    setFilters(resetFilters)
    onFilterData && onFilterData(resetFilters)
  }

  // 处理编辑
  const handleEdit = (record) => {
    setEditingRecord(record)
    editForm.setFieldsValue({
      ...record,
      date: dayjs(record.date),
    })
    setModalVisible(false)
    setEditModalVisible(true)
  }

  // 处理编辑提交
  const handleEditSubmit = async (values) => {
    setLoading(true)
    try {
      const updatedRecord = {
        ...values,
        date: values.date.format('YYYY-MM-DD'),
        hours: values.hours || 0,
        remaining: values.remaining || 0,
        content: values.content || '',
        object: values.object || '',
        product: values.product || '',
        executor: values.executor || '',
        project: values.project || '',
      }

      if (!validateWorkTimeData(updatedRecord)) {
        message.error('数据验证失败，请检查必填项')
        return
      }

      onEditRecord(editingRecord.id, updatedRecord)
      setEditModalVisible(false)
      setEditingRecord(null)
      editForm.resetFields()
      message.success('记录更新成功')
    } catch (error) {
      console.error('更新记录失败:', error)
      message.error('更新失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div>
      <div style={{ marginBottom: '16px' }}>
        <Space>
          <CalendarOutlined />
          <Text strong>日历视图</Text>
          <Text type='secondary'>点击有数据的日期查看详情</Text>
        </Space>
      </div>

      {/* 筛选器 */}
      <Card size='small' style={{ marginBottom: '16px' }}>
        <div
          style={{
            display: 'flex',
            gap: '16px',
            alignItems: 'center',
            flexWrap: 'wrap',
          }}
        >
          <div style={{ flex: 1, minWidth: '200px' }}>
            <Input
              placeholder='搜索工作内容'
              value={filters.keyword}
              onChange={(e) =>
                setFilters((prev) => ({ ...prev, keyword: e.target.value }))
              }
              allowClear
            />
          </div>

          <div style={{ minWidth: '120px' }}>
            <Select
              placeholder='选择项目'
              value={filters.project}
              onChange={(value) =>
                setFilters((prev) => ({ ...prev, project: value }))
              }
              style={{ width: '100%' }}
              allowClear
            >
              <Select.Option value='all'>全部项目</Select.Option>
              {filterOptions.projects.map((project) => (
                <Select.Option key={project} value={project}>
                  {project}
                </Select.Option>
              ))}
            </Select>
          </div>

          <div style={{ minWidth: '120px' }}>
            <Select
              placeholder='选择产品'
              value={filters.product}
              onChange={(value) =>
                setFilters((prev) => ({ ...prev, product: value }))
              }
              style={{ width: '100%' }}
              allowClear
            >
              <Select.Option value='all'>全部产品</Select.Option>
              {filterOptions.products.map((product) => (
                <Select.Option key={product} value={product}>
                  {product}
                </Select.Option>
              ))}
            </Select>
          </div>

          <div>
            <Space>
              <Button
                type='primary'
                icon={<SearchOutlined />}
                onClick={handleFilter}
              >
                搜索
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleResetFilter}>
                重置
              </Button>
            </Space>
          </div>
        </div>
      </Card>

      {/* 工时提示图例 */}
      <Card size='small' style={{ marginBottom: '16px' }}>
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: '20px',
            flexWrap: 'wrap',
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <CheckCircleOutlined
              style={{ color: '#52c41a', fontSize: '16px' }}
            />
            <span style={{ fontSize: '12px', color: '#666' }}>已完成(≥8h)</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <ExclamationCircleOutlined
              style={{ color: '#fa8c16', fontSize: '16px' }}
            />
            <span style={{ fontSize: '12px', color: '#666' }}>
              当日不足(&lt;8h)
            </span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <WarningOutlined style={{ color: '#ff4d4f', fontSize: '16px' }} />
            <span style={{ fontSize: '12px', color: '#666' }}>逾期未完成</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <ClockCircleOutlined
              style={{ color: '#1890ff', fontSize: '16px' }}
            />
            <span style={{ fontSize: '12px', color: '#666' }}>周末/节假日</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <ExclamationCircleOutlined
              style={{ color: '#fa8c16', fontSize: '16px' }}
            />
            <span style={{ fontSize: '12px', color: '#666' }}>待录入</span>
          </div>
        </div>
      </Card>

      <Calendar
        cellRender={cellRender}
        onSelect={handleDateClick}
        onPanelChange={handlePanelChange}
        style={{
          border: '1px solid #d9d9d9',
          borderRadius: '8px',
          padding: '16px',
        }}
      />

      {/* 日期详情模态框 */}
      <Modal
        title={
          <Space>
            <CalendarOutlined />
            <span>{selectedDate?.format('YYYY年MM月DD日')} 工时记录</span>
          </Space>
        }
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={800}
      >
        {selectedDateData.length > 0 && (
          <div>
            <div style={{ marginBottom: '16px' }}>
              <Space>
                <Badge
                  count={selectedDateData.length}
                  style={{ backgroundColor: '#52c41a' }}
                />
                <Text>共 {selectedDateData.length} 条记录</Text>
                <Text type='secondary'>|</Text>
                <Text>
                  总工时:{' '}
                  {selectedDateData.reduce(
                    (sum, item) => sum + (item.hours || 0),
                    0
                  )}{' '}
                  小时
                </Text>
              </Space>
            </div>

            <List
              dataSource={selectedDateData}
              renderItem={(item) => (
                <List.Item
                  actions={[
                    <Tooltip key='edit' title='编辑'>
                      <a onClick={() => handleEdit(item)}>编辑</a>
                    </Tooltip>,
                    <Tooltip key='delete' title='删除'>
                      <a
                        style={{ color: '#ff4d4f' }}
                        onClick={() => {
                          setModalVisible(false)
                          onDeleteRecord && onDeleteRecord(item.id)
                        }}
                      >
                        删除
                      </a>
                    </Tooltip>,
                  ]}
                >
                  <List.Item.Meta
                    avatar={
                      <Badge
                        count={`${item.hours}h`}
                        style={{ backgroundColor: '#1890ff' }}
                      />
                    }
                    title={
                      <Space>
                        <Text strong>{item.content}</Text>
                        {item.project && (
                          <Tag color='green'>{item.project}</Tag>
                        )}
                        {item.product && <Tag color='blue'>{item.product}</Tag>}
                      </Space>
                    }
                    description={
                      <Space direction='vertical' size='small'>
                        {item.object && (
                          <Text type='secondary'>对象: {item.object}</Text>
                        )}
                        {item.executor && (
                          <Text type='secondary'>执行: {item.executor}</Text>
                        )}
                        {item.remaining > 0 && (
                          <Text type='secondary'>剩余: {item.remaining}h</Text>
                        )}
                      </Space>
                    }
                  />
                </List.Item>
              )}
            />
          </div>
        )}
      </Modal>

      {/* 编辑模态框 */}
      <Modal
        title={
          <Space>
            <EditOutlined />
            <span>编辑工时记录</span>
          </Space>
        }
        open={editModalVisible}
        onOk={() => editForm.submit()}
        onCancel={() => {
          setEditModalVisible(false)
          setEditingRecord(null)
          editForm.resetFields()
        }}
        width={800}
        confirmLoading={loading}
      >
        <Form form={editForm} layout='vertical' onFinish={handleEditSubmit}>
          <Form.Item
            name='date'
            label='日期'
            rules={[{ required: true, message: '请选择日期' }]}
          >
            <DatePicker style={{ width: '100%' }} format='YYYY-MM-DD' />
          </Form.Item>

          <Form.Item
            name='content'
            label='工作内容'
            rules={[
              { required: true, message: '请输入工作内容' },
              { min: 5, message: '工作内容至少5个字符' },
            ]}
          >
            <TextArea rows={3} showCount maxLength={500} />
          </Form.Item>

          <div style={{ display: 'flex', gap: '16px' }}>
            <Form.Item
              name='hours'
              label='耗时（小时）'
              rules={[
                { required: true, message: '请输入耗时' },
                {
                  type: 'number',
                  min: 0,
                  max: 24,
                  message: '耗时必须在0-24小时之间',
                },
              ]}
              style={{ flex: 1 }}
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                max={24}
                step={0.5}
                precision={1}
              />
            </Form.Item>

            <Form.Item
              name='remaining'
              label='剩余（小时）'
              rules={[
                { type: 'number', min: 0, message: '剩余时间不能为负数' },
              ]}
              style={{ flex: 1 }}
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                step={0.5}
                precision={1}
              />
            </Form.Item>
          </div>

          <Form.Item name='object' label='对象'>
            <Input />
          </Form.Item>

          <div style={{ display: 'flex', gap: '16px' }}>
            <Form.Item name='product' label='产品' style={{ flex: 1 }}>
              <Input />
            </Form.Item>

            <Form.Item name='executor' label='执行' style={{ flex: 1 }}>
              <Input />
            </Form.Item>
          </div>

          <Form.Item name='project' label='项目'>
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default WorkTimeCalendar
